package com.fast.framework.config.security.customize;

import cn.hutool.core.util.StrUtil;
import com.fast.framework.constant.HttpStatus;
import com.fast.framework.utils.ServletUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 当未登录或token失效访问接口时,自定义的返回结果。引用的位置：SecurityConfig文件里的 `configure(HttpSecurity http)-> http.exceptionHandling()`
 * </p>
 *
 * @author lanyuankeji
 */
@Component("authenticationEntryPoint")
public class AuthenticationEntryPoint implements org.springframework.security.web.AuthenticationEntryPoint {
    /**
     * 处理未登录的情况
     *
     * @param request       HTTP 请求对象
     * @param response      HTTP 响应对象
     * @param authException 认证异常
     * @throws IOException      IO 异常
     * @throws ServletException Servlet 异常
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String msg = StrUtil.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        ServletUtils.renderObject(response, HttpStatus.UNAUTHORIZED, msg);
    }

}
